package com.example.flower_shop.service.impl;

import com.example.flower_shop.entity.CartItem;
import com.example.flower_shop.entity.Product;
import com.example.flower_shop.entity.User;
import com.example.flower_shop.exception.BusinessException;
import com.example.flower_shop.exception.ResourceNotFoundException;
import com.example.flower_shop.repository.CartItemRepository;
import com.example.flower_shop.repository.ProductRepository;
import com.example.flower_shop.repository.UserRepository;
import com.example.flower_shop.service.CartService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.Iterator;
import java.util.List;

@Service
@Transactional(readOnly = true)
@Slf4j
public class CartServiceImpl extends BaseServiceImpl<CartItem, Long> implements CartService {

    private final CartItemRepository cartItemRepository;
    private final UserRepository userRepository;
    private final ProductRepository productRepository;

    public CartServiceImpl(CartItemRepository cartItemRepository,
            UserRepository userRepository,
            ProductRepository productRepository) {
        super(cartItemRepository);
        this.cartItemRepository = cartItemRepository;
        this.userRepository = userRepository;
        this.productRepository = productRepository;
    }

    @Override
    public List<CartItem> findByUserId(Long userId) {
        List<CartItem> cartItems = cartItemRepository.findByUserId(userId);
        Iterator<CartItem> iterator = cartItems.iterator();

        while (iterator.hasNext()) {
            CartItem item = iterator.next();
            try {
                Product product = productRepository.findById(item.getProduct().getId())
                        .orElse(null);

                // 如果商品不存在或已下架，从购物车中移除
                if (product == null || product.getStatus() != 1) {
                    cartItemRepository.delete(item);
                    iterator.remove();
                }
            } catch (Exception e) {
                // 如果获取商品信息失败，也从购物车中移除
                cartItemRepository.delete(item);
                iterator.remove();
            }
        }

        return cartItems;
    }

    @Override
    @Transactional
    public CartItem addToCart(Long userId, Long productId, Integer quantity) {
        log.info("开始添加商品到购物车 - 用户ID: {}, 商品ID: {}, 数量: {}", userId, productId, quantity);

        // 检查用户是否存在
        User user = userRepository.findById(userId)
                .orElseThrow(() -> {
                    log.error("用户不存在 - 用户ID: {}", userId);
                    return new ResourceNotFoundException("用户", userId);
                });
        log.info("找到用户 - 用户ID: {}, 用户名: {}", user.getId(), user.getUsername());

        // 检查商品是否存在
        Product product = productRepository.findById(productId)
                .orElseThrow(() -> {
                    log.error("商品不存在 - 商品ID: {}", productId);
                    return new ResourceNotFoundException("商品", productId);
                });
        log.info("找到商品 - 商品ID: {}, 商品名: {}, 状态: {}, 库存: {}",
                product.getId(), product.getName(), product.getStatus(), product.getStock());

        // 检查商品是否上架
        if (product.getStatus() != 1) {
            log.warn("商品已下架 - 商品ID: {}, 商品名: {}", product.getId(), product.getName());
            throw new BusinessException("PRODUCT_UNAVAILABLE", "商品已下架");
        }

        // 检查库存
        if (product.getStock() < quantity) {
            log.warn("商品库存不足 - 商品ID: {}, 商品名: {}, 当前库存: {}, 需求数量: {}",
                    product.getId(), product.getName(), product.getStock(), quantity);
            throw new BusinessException("INSUFFICIENT_STOCK", "商品库存不足");
        }

        // 检查购物车中是否已存在该商品
        CartItem cartItem = cartItemRepository.findByUserIdAndProductId(userId, productId)
                .orElseGet(() -> {
                    log.info("创建新的购物车项 - 用户ID: {}, 商品ID: {}", userId, productId);
                    CartItem newItem = new CartItem();
                    newItem.setUser(user);
                    newItem.setProduct(product);
                    return newItem;
                });

        if (cartItem.getId() == null) {
            // 新增商品到购物车
            cartItem.setQuantity(quantity);
            log.info("设置新购物车项数量 - 数量: {}", quantity);
        } else {
            // 如果已存在，增加数量
            int newQuantity = cartItem.getQuantity() + quantity;
            log.info("更新购物车项数量 - 原数量: {}, 新增数量: {}, 总数量: {}",
                    cartItem.getQuantity(), quantity, newQuantity);

            if (product.getStock() < newQuantity) {
                log.warn("商品库存不足 - 商品ID: {}, 商品名: {}, 当前库存: {}, 需求总数量: {}",
                        product.getId(), product.getName(), product.getStock(), newQuantity);
                throw new BusinessException("INSUFFICIENT_STOCK", "商品库存不足");
            }
            cartItem.setQuantity(newQuantity);
        }

        CartItem savedCartItem = cartItemRepository.save(cartItem);
        log.info("保存购物车项成功 - 购物车项ID: {}, 用户ID: {}, 商品ID: {}, 数量: {}",
                savedCartItem.getId(), userId, productId, savedCartItem.getQuantity());

        return savedCartItem;
    }

    @Override
    @Transactional
    public CartItem updateQuantity(Long userId, Long productId, Integer quantity) {
        CartItem cartItem = cartItemRepository.findByUserIdAndProductId(userId, productId)
                .orElseThrow(() -> new BusinessException("CART_ITEM_NOT_FOUND", "购物车中不存在该商品"));

        Product product = cartItem.getProduct();

        // 检查商品是否上架
        if (product.getStatus() != 1) {
            throw new BusinessException("PRODUCT_UNAVAILABLE", "商品已下架");
        }

        // 检查库存
        if (product.getStock() < quantity) {
            throw new BusinessException("INSUFFICIENT_STOCK", "商品库存不足");
        }

        cartItem.setQuantity(quantity);
        return cartItemRepository.save(cartItem);
    }

    @Override
    @Transactional
    public void removeFromCart(Long userId, Long cartItemId) {
        // 先检查购物车项是否存在
        CartItem cartItem = cartItemRepository.findById(cartItemId)
                .orElseThrow(() -> new BusinessException("CART_ITEM_NOT_FOUND", "购物车中不存在该商品"));

        // 确保购物车项属于当前用户
        if (!cartItem.getUser().getId().equals(userId)) {
            throw new BusinessException("UNAUTHORIZED", "无权访问此购物车项");
        }

        // 执行删除操作
        cartItemRepository.delete(cartItem);
        cartItemRepository.flush(); // 确保立即执行删除
    }

    @Override
    @Transactional
    public void clearCart(Long userId) {
        List<CartItem> cartItems = cartItemRepository.findByUserId(userId);
        cartItemRepository.deleteAll(cartItems);
    }

    @Override
    public int countByUserId(Long userId) {
        return cartItemRepository.countByUserId(userId);
    }

    @Override
    public boolean checkProductInCart(Long userId, Long productId) {
        return cartItemRepository.findByUserIdAndProductId(userId, productId).isPresent();
    }

    @Override
    public void checkCartItemBelongsToUser(Long cartItemId, Long userId) {
        CartItem cartItem = cartItemRepository.findById(cartItemId)
                .orElseThrow(() -> new ResourceNotFoundException("购物车项", cartItemId));

        if (!cartItem.getUser().getId().equals(userId)) {
            throw new BusinessException("UNAUTHORIZED", "无权访问此购物车项");
        }
    }

    @Override
    @Transactional
    public void checkAndUpdateCartItems(Long userId) {
        List<CartItem> cartItems = cartItemRepository.findByUserId(userId);
        Iterator<CartItem> iterator = cartItems.iterator();

        while (iterator.hasNext()) {
            CartItem item = iterator.next();
            Product product = item.getProduct();

            // 检查商品是否已下架或库存不足
            if (product.getStatus() != 1 || product.getStock() < item.getQuantity()) {
                cartItemRepository.delete(item);
                iterator.remove();
            }
        }
    }
}